﻿using Compass.Maui.Pages.FinishGoods;

namespace Compass.Maui.Controls;
/// <summary>
/// 主计划搜索页面
/// </summary>
public class MainPlanSearchHandler:SearchHandler
{
    protected override async void OnQueryChanged(string oldValue, string newValue)
    {
        base.OnQueryChanged(oldValue, newValue);
        await IsBusyFor(async () =>
        {
            if (string.IsNullOrWhiteSpace(newValue))
            {
                ItemsSource = null;
            }
            else
            {
                //获从依赖注入容器中获取对象
                var service = Ioc.Default.GetRequiredService<IMainPlanService>();
                ItemsSource = await service.GetMainPlansAsync(0, 10, newValue);
            }
        });
    }

    protected override async void OnItemSelected(object item)
    {
        base.OnItemSelected(item);
        if (item is not MainPlanDto mainPlanDto) return;
        await Shell.Current.GoToAsync(nameof(PackingInfoPage),
            new Dictionary<string, object>()
            {
                {nameof(MainPlanDto),mainPlanDto}
            });
    }

    #region IsBusy
    private long _isBusy;
    public bool IsBusy => Interlocked.Read(ref _isBusy) > 0;

    public async Task IsBusyFor(Func<Task> unitOfWork)
    {
        Interlocked.Increment(ref _isBusy);
        OnPropertyChanged(nameof(IsBusy));

        try
        {
            await unitOfWork();
        }
        finally
        {
            Interlocked.Decrement(ref _isBusy);
            OnPropertyChanged(nameof(IsBusy));
        }
    }
    #endregion
}